<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>webSocketDemo</title>
</head>
<body>


    <div id="result" style="height: 200px;border: 1px solid blue;overflow-y:auto"></div>
    <div id="inputDiv">
        <input type="text" id="info">
        <input type="button" value="发送" id="sbut">
    </div>
    <script>


    </script>

    <script type="text/javascript">

        var wsobj = null;
        var flag = true;
        var url = "ws://localhost:8080/h5Demo/echo"; // 记住这里一定要路径写对哦
        // 用来创建连接websocket对象
        function create() {
            if("WebSocket" in window){
                wsobj = new WebSocket(url);
            }else{
                if("MozWebSocket" in window){
                    wsobj = new MozWebSocket(url);
                }else{
                    alert("您的浏览器不支持webSocket");
                }
            }
        }

        window.onload = function(){
            create();
            wsobj.onopen = function(e){
                document.querySelector("#result").innerHTML = "连接打开!";
            }

            wsobj.onclose = function(e){
                document.querySelector("#result").innerHTML = "连接关闭!";
            }

            document.querySelector("#sbut").addEventListener("click",function(){

                // 点击发送按钮
                var info = document.querySelector("#info").value;
                wsobj.send(info);
                wsobj.onmessage = function(e){
                    if(flag){
                        document.querySelector("#result").innerHTML = "";
                        flag = false;
                    }
                    document.querySelector("#result").innerHTML+= ("收到后台发来的数据:" + e.data+"<br/>");
                }

            },false);


        }


    </script>



</body>
</html>